import json
import requests
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5


def base64_api(img):
    data = {"username": 'caixukun666', "password": 'Afrt3358079', "typeid": 3, "image": img}
    result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]


session = requests.session()

session.headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
}

session.get("https://user.wangxiao.cn/login?url=https%3a%2f%2fk.wangxiao.cn%2fuser%2f")

print(session.cookies)

img_resp = session.post("https://user.wangxiao.cn/apis//common/getImageCaptcha",
                        headers={
                            "content-type": "application/json;charset=UTF-8"
                        })

b64str = img_resp.json()['data'].split(',')[1]

with open('captcha.png', 'wb') as f:
    f.write(base64.b64decode(b64str))

res = base64_api(b64str)
print(res)

uname = "18954474219"
pwd = "cxkngm250"

time_resp = session.post('https://user.wangxiao.cn/apis//common/getTime',
                         headers={
                             'Content-Type': 'application/json;charset=UTF-8'
                         })
tm = time_resp.json()['data']  # 与pwd一起进行加密 所以要先获取到该值
print(tm)

publickey_str = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA5Zq6ZdH/RMSvC8WKhp5gj6Ue4Lqjo0Q2PnyGbSkTlYku0HtVzbh3S9F9oHbxeO55E8tEEQ5wj/+52VMLavcuwkDypG66N6c1z0Fo2HgxV3e0tqt1wyNtmbwg7ruIYmFM+dErIpTiLRDvOy+0vgPcBVDfSUHwUSgUtIkyC47UNQIDAQAB"

pub_key = RSA.import_key(base64.b64decode(publickey_str))
rsa = PKCS1_v1_5.new(pub_key)
pwd_res = rsa.encrypt((pwd + str(tm)).encode('utf-8'))
pwd_b64 = base64.b64encode(pwd_res).decode()

login_url = "https://user.wangxiao.cn/apis//login/passwordLogin"
data = {
    "userName": uname,
    "password": pwd_b64,
    "imageCaptchaCode": res
}

login_resp = session.post(login_url, data=json.dumps(data), headers={
    'Content-Type': 'application/json;charset=UTF-8'
})

print(login_resp.text)
#  虽然请求成功 但是还需要对cookie进行处理
login_info = login_resp.json()['data']
session.cookies['autoLogin'] = "true"
session.cookies['userInfo'] = json.dumps(login_info)
session.cookies['token'] = login_info['token']
session.cookies["UserCookieName"] = login_info['userName']
session.cookies["OldUsername2"] = login_info['userNameCookies']
session.cookies["OldUsername"] = login_info['userNameCookies']
session.cookies["OldPassword"] = login_info['passwordCookies']

session.cookies["UserCookieName_"] = login_info['userName']
session.cookies["OldUsername2_"] = login_info['userNameCookies']
session.cookies["OldUsername_"] = login_info['userNameCookies']
session.cookies["OldPassword_"] = login_info['passwordCookies']

session.cookies[login_info['userName'] + "_exam"] = login_info['sign']

#   测试
get_data_url = "https://ks.wangxiao.cn/TestPaper/getPaperRuleQuestions"
resp_dat = session.post(get_data_url, data='{"id":"E84C925A-2918-4A3A-B6F7-B94BAB4D2592"}', headers={
    'Content-Type': 'application/json;charset=UTF-8'
})

print(resp_dat.json())

#  成功拿到题目数据 模拟登录是成功的